package com.tdam.CommunicationManager;

import java.util.ArrayList;
import java.util.Date;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ViewAnimator;

public class WebMail extends AnimatedActivity {

	private DbInterface db;
	private ListView lstMessageListFromContact;
	private InfoAdapter messagesAdapter;
	private ServerConnection server;
	private WebMailInfo selectedContactMessages;
	private boolean editMode;
	private Button btmEdit;
	private Button btmAction;
	private Button btmEditMessages;
	private Button btmBack;
	private LinearLayout lytDelete;
	private LinearLayout lytMessages;
	private static int notificationId = 0;

	@Override
	protected void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
		setContentView(R.layout.web_mail_view);
		editMode = false;
		views = (ViewAnimator) findViewById(R.id.viewWebMails);
		_adapter = new InfoAdapter<WebMailInfo, WebMailHolder>(this,
				R.layout.web_mail_item, WebMailHolder.class);
		messagesAdapter = new InfoAdapter<WebMailInfo, WebMailInfoHolder>(this,
				R.layout.web_mail_text_item, WebMailInfoHolder.class);
		getListView().setAdapter(_adapter);
		getListView().setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1,
					int position, long arg3) {
				onContactSelected(position);
			}
		});

		lstMessageListFromContact = (ListView) findViewById(R.id.lstmessageListFromContact);
		lstMessageListFromContact.setAdapter(messagesAdapter);
		lstMessageListFromContact.setDivider(null);
		lstMessageListFromContact
				.setOnItemClickListener(new OnItemClickListener() {
					@Override
					public void onItemClick(AdapterView<?> arg0, View arg1,
							int position, long arg3) {
						if (editMode)
							onMessageSelected(position);
					}
				});

		// if(User.db==null)User.db=new DbInterface(this);
		db = User.db;
		server = User.server;
		ArrayList<WebMailInfo> messages = db.getLastMessageForContacts();
		for (WebMailInfo item : messages)
			_adapter.addItem(item);

		btmEdit = (Button) findViewById(R.id.btmEdit);
		btmEdit.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				if (editMode)
					onExitEditMode();
				else
					onEditMode();
			}
		});

		btmEditMessages = (Button) findViewById(R.id.btmEditMessages);
		btmEditMessages.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				if (editMode)
					onExitEditModeMessages();
				else
					onEditModeMessages();
			}
		});

		lytMessages = (LinearLayout) findViewById(R.id.lytMessages);
		lytDelete = (LinearLayout) findViewById(R.id.lytDelete);

		Button btmDelete = (Button) findViewById(R.id.btmDelete);
		btmDelete.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				onDeleteSingleMessages();
			}
		});

		btmBack = (Button) findViewById(R.id.btmBack);
		btmBack.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				onBack();
			}
		});

		Button btmSend = (Button) findViewById(R.id.btmSend);
		btmSend.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				onSendMessage((Button) v);
			}
		});

		btmAction = (Button) findViewById(R.id.btmRenew);
		btmAction.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				if (editMode)
					onDelete();
				else
					onRenew();
			}
		});

	}

	private void onExitEditMode() {
		editMode = false;
		btmEdit.setText(getString(R.string.edit));
		btmAction.setText(R.string.renew);
		int elementsCounter = _adapter.getAllCount() - 1;
		for (; elementsCounter > -1; --elementsCounter)
			((WebMailInfo) _adapter.getItemFromOriginal(elementsCounter)).edit = EditStatus.NOT_EDIT;
		_adapter.notifyDataSetChanged();

	}

	private void onEditMode() {
		editMode = true;
		btmEdit.setText(getString(R.string.End));
		btmAction.setText(R.string.delete);
		int elementsCounter = _adapter.getAllCount() - 1;
		for (; elementsCounter > -1; --elementsCounter)
			((WebMailInfo) _adapter.getItemFromOriginal(elementsCounter)).edit = EditStatus.EDIT_NOT_MARKED;
		_adapter.notifyDataSetChanged();

	}

	private void onExitEditModeMessages() {
		editMode = false;
		btmEditMessages.setText(getString(R.string.edit));
		btmBack.setEnabled(true);
		lytMessages.setVisibility(View.VISIBLE);
		lytDelete.setVisibility(View.GONE);
		int elementsCounter = messagesAdapter.getAllCount() - 1;
		for (; elementsCounter > -1; --elementsCounter)
			((WebMailInfo) messagesAdapter.getItemFromOriginal(elementsCounter)).edit = EditStatus.NOT_EDIT;
		messagesAdapter.notifyDataSetChanged();

	}

	private void onEditModeMessages() {
		editMode = true;
		btmEditMessages.setText(getString(R.string.End));
		btmBack.setEnabled(false);
		lytDelete.setVisibility(View.VISIBLE);
		lytMessages.setVisibility(View.GONE);
		int elementsCounter = messagesAdapter.getAllCount() - 1;
		for (; elementsCounter > -1; --elementsCounter)
			((WebMailInfo) messagesAdapter.getItemFromOriginal(elementsCounter)).edit = EditStatus.EDIT_NOT_MARKED;

		messagesAdapter.notifyDataSetChanged();

	}

	private void onBack() {
		ArrayList<WebMailInfo> messages = db.getLastMessageForContacts();
		_adapter.clear();
		messages = db.getLastMessageForContacts();
		for (WebMailInfo item : messages)
			_adapter.addItem(item);
		_adapter.notifyDataSetChanged();
		previousView();
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
	}

	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
	}

	private void onRenew() {
		WebMailInfo lastelement = null;
		Date lastRenew = null;
		try {
			lastelement = ((WebMailInfo) _adapter.getItem(0));
			lastRenew = lastelement.timeStamp;
		} catch (IndexOutOfBoundsException e) {
			lastRenew = new Date(0);
		}
		ArrayList<WebMailInfo> messages = server.getMessages(lastRenew);
		db.saveMessages(messages);
		_adapter.clear();
		messages = db.getLastMessageForContacts();
		for (WebMailInfo item : messages)
			_adapter.addItem(item);
		_adapter.notifyDataSetChanged();
	}

	private void onDelete() {
		int elementsCounter = _adapter.getCount() - 1;
		WebMailInfo temp;
		for (; elementsCounter > -1; --elementsCounter) {
			temp = (WebMailInfo) _adapter.getItem(elementsCounter);
			if (temp.edit == EditStatus.EDIT_MARKED) {
				db.deleteMessages(temp.user);
				_adapter.remove(elementsCounter);
			}

		}

		_adapter.notifyDataSetChanged();
	}

	private void onDeleteSingleMessages() {
		int elementsCounter = messagesAdapter.getCount() - 1;
		WebMailInfo temp;
		for (; elementsCounter > -1; --elementsCounter) {
			temp = (WebMailInfo) messagesAdapter.getItem(elementsCounter);
			if (temp.edit == EditStatus.EDIT_MARKED) {
				db.deleteSingleMessage(temp);
				messagesAdapter.remove(elementsCounter);
			}

		}
		messagesAdapter.notifyDataSetChanged();
	}

	private void onSendMessage(Button btmSend) {
		TextView txtSendMessage = (TextView) findViewById(R.id.txtSendMessage);
		btmSend.setClickable(false);
		String message = txtSendMessage.getText().toString();
		if (message.compareTo("") != 0) {
			txtSendMessage.setText("");
			WebMailInfo messageSend = new WebMailInfo(
					selectedContactMessages.user, message, new Date(), false);
			boolean sucess = server.sendMessage(messageSend);
			if (sucess) {
				ArrayList<WebMailInfo> messages = new ArrayList<WebMailInfo>();
				messages.add(messageSend);
				db.saveMessages(messages);
				messagesAdapter.addItem(messageSend);
				messagesAdapter.notifyDataSetChanged();
				lstMessageListFromContact
						.smoothScrollToPosition(messagesAdapter.getCount() - 1);

			}

			NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
			Notification messageStatus = new Notification(R.drawable.vignette,
					getString((sucess ? R.string.sendMessageOk
							: R.string.sendMessageFail)), new Date().getTime());
			messageStatus.flags = Notification.FLAG_AUTO_CANCEL;
			Context context = getApplicationContext();
			CharSequence contentTitle = "";
			CharSequence contentText = "";
			// Intent notificationIntent = new Intent(this, WebMail.class);
			PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
					null, 0);
			messageStatus.setLatestEventInfo(context, contentTitle,
					contentText, contentIntent);
			notificationManager.notify(++notificationId, messageStatus);
		}

		btmSend.setClickable(true);
		// Toast.makeText(this, "Enviando", Toast.LENGTH_SHORT).show();
	}

	private void onContactSelected(int position) {
		if (editMode) {
			WebMailInfo temp = (WebMailInfo) _adapter.getItem(position);
			temp.edit = (temp.edit == EditStatus.EDIT_NOT_MARKED) ? EditStatus.EDIT_MARKED
					: EditStatus.EDIT_NOT_MARKED;
			_adapter.notifyDataSetChanged();

		} else {
			this.selectedContactMessages = (WebMailInfo) _adapter
					.getItem(position);
			messagesAdapter.clear();
			ArrayList<WebMailInfo> allMessages = db
					.getMessages(selectedContactMessages.user);
			for (WebMailInfo item : allMessages)
				messagesAdapter.addItem(item);

			lstMessageListFromContact.smoothScrollToPosition(messagesAdapter
					.getCount() - 1);
			nextView();
			Cursor contactCursor = getContentResolver().query(
					ContactsContract.Data.CONTENT_URI,
					null,
					ContactsContract.Data.DATA1 + " = ? AND "
							+ ContactsContract.Data.MIMETYPE + " = ?",
					new String[] { selectedContactMessages.user,
							DbInterface.MIMETYPE_WEBMAIL }, null);
			String nameView = selectedContactMessages.user;
			boolean associatedContact = contactCursor.moveToNext();
			if (associatedContact) {
				int contactId = contactCursor.getInt(contactCursor
						.getColumnIndex(ContactsContract.Data.RAW_CONTACT_ID));
				contactCursor.close();
				contactCursor = getContentResolver().query(
						ContactsContract.Contacts.CONTENT_URI, null,
						ContactsContract.Contacts._ID + "=?",
						new String[] { String.valueOf(contactId) }, null);
				if (contactCursor.moveToNext()) {
					nameView = contactCursor
							.getString(contactCursor
									.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
				}
				contactCursor.close();
			}
			TextView txtInfoContactName = (TextView) findViewById(R.id.txtInfoContactName);
			txtInfoContactName.setText(nameView);
		}
	}

	private void onMessageSelected(int position) {
		WebMailInfo temp = (WebMailInfo) messagesAdapter.getItem(position);
		temp.edit = (temp.edit == EditStatus.EDIT_NOT_MARKED) ? EditStatus.EDIT_MARKED
				: EditStatus.EDIT_NOT_MARKED;
		messagesAdapter.notifyDataSetChanged();
	}
}